﻿<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 表格工具栏 -->
            <form class="layui-form toolbar" lay-filter="userTbSearchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">账&emsp;号:</label>
                        <div class="layui-input-inline">
                            <input name="username" class="layui-input" placeholder="输入账号"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">用户名:</label>
                        <div class="layui-input-inline">
                            <input name="nickName" class="layui-input" placeholder="输入用户名"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">性&emsp;别:</label>
                        <div class="layui-input-inline">
                            <select name="sex"></select>
                        </div>
                    </div>
                    <div class="layui-inline">&emsp;
                        <button class="layui-btn icon-btn" lay-filter="userTbSearch" lay-submit>
                            <i class="layui-icon">&#xe615;</i>搜索
                        </button>
                    </div>
                </div>
            </form>
            <!-- 数据表格 -->
            <table id="userTable" lay-filter="userTable"></table>
        </div>
    </div>
</div>
<!-- 表格操作列 -->
<script type="text/html" id="userTbBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit" perm-show="sys:user:update">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs"
       data-dropdown="#userTbDelDrop{{d.LAY_INDEX}}" no-shade="true">删除</a>
    <a class="layui-btn layui-btn-xs" lay-event="reset">重置密码</a>
    <div class="dropdown-menu-nav dropdown-popconfirm dropdown-top-right layui-hide"
         id="userTbDelDrop{{d.LAY_INDEX}}"
         style="max-width: 200px;white-space: normal;min-width: auto;margin-left: 10px;">
        <div class="dropdown-anchor"></div>
        <div class="dropdown-popconfirm-title">
            <i class="layui-icon layui-icon-help"></i>
            确定要删除{{d.nickName}}吗？
        </div>
        <div class="dropdown-popconfirm-btn">
            <a class="layui-btn" btn-cancel>取消</a>
            <a class="layui-btn layui-btn-normal" lay-event="del">确定</a>
        </div>
    </div>
</script>
<!-- 表格状态列 -->
<script type="text/html" id="userTbState">
    <input type="checkbox" lay-filter="userTbStateCk" value="{{d.userId}}" lay-skin="switch"
           lay-text="正常|锁定" {{d.state==0?'checked':''}}/>
</script>
<!-- 表单弹窗 -->
<script type="text/html" id="userEditDialog">
    <form id="userEditForm" lay-filter="userEditForm" class="layui-form model-form">
        <input name="userId" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">账号:</label>
            <div class="layui-input-block">
                <input name="username" placeholder="请输入账号" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">用户名:</label>
            <div class="layui-input-block">
                <input name="nickName" placeholder="请输入用户名" class="layui-input"
                       lay-verType="tips" lay-verify="" />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">性别:</label>
            <div class="layui-input-block">
                <select name="sex" lay-verType="tips" lay-verify="" required></select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号:</label>
            <div class="layui-input-block">
                <input name="phone" placeholder="请输入手机号" class="layui-input"
                       lay-verType="tips" lay-verify="phoneX" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">角色:</label>
            <div class="layui-input-block">
                <div id="userEditRoleSel"></div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">登录密码:</label>
            <div class="layui-input-block">
                <input name="password" type="password" placeholder="请输入登录密码" class="layui-input"
                       lay-verType="tips" lay-verify="required|password" required/>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="userEditSubmit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>
<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'tableX', 'util', 'admin', 'xmSelect', 'formX', 'dropdown', 'upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var tableX = layui.tableX;
        var util = layui.util;
        var admin = layui.admin;
        var formX = layui.formX;
        var setter = layui.setter;
        var xmSelect = layui.xmSelect;
        var roleList = [];  // 所有角色
        form.render('select', 'userTbSearchForm');

        /* 渲染表格 */
        var insTb = tableX.render({
            elem: '#userTable',
            url: setter.baseServer + 'sys/user/page',
            page: true,
            height: 'full-235',
            limits: [10,20,30,50,80,100,200],
            limit: 30, //每页默认显示的数量
            toolbar: ['<p>',
                '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>&nbsp;',
                '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn"><i class="layui-icon">&#xe640;</i>删除</button>&nbsp;',
                '<button lay-event="import" class="layui-btn layui-btn-sm layui-btn-warm icon-btn"><i class="layui-icon">&#xe681;</i>导入</button>',
                '</p>'].join(''),
            cellMinWidth: 100,
            cols: [[
                {type: 'checkbox'},
                {type: 'numbers'},
                {field: 'username', title: '账号', sort: true},
                {field: 'nickName', title: '用户名', sort: true},
                {field: 'sexName', title: '性别', sort: true},
                {field: 'phone', title: '手机号', sort: true},
                {
                    field: 'roleName', title: '角色', templet: function (d) {
                        return d.roles.map(function (item) {
                            return '<span class="layui-badge layui-badge-gray">' + item.roleName + '</span>';
                        }).join('&nbsp;&nbsp;');
                    }, sort: true, width: 150
                },
                {
                    field: 'createTime', title: '创建时间', templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, sort: true, width: 160
                },
                {field: 'state', title: '状态', templet: '#userTbState', sort: true, width: 100},
                {title: '操作', toolbar: '#userTbBar', align: 'center', minWidth: 200, fixed: 'right'}
            ]]
        });

        /* 表格搜索 */
        form.on('submit(userTbSearch)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}});
            return false;
        });

        /* 表格工具条点击事件 */
        table.on('tool(userTable)', function (obj) {
            if ('edit' === obj.event) { // 修改
                showEditModel(obj.data);
            } else if ('del' === obj.event) { // 删除
                doDel(obj);
            } else if ('reset' === obj.event) { // 重置密码
                admin.prompt({formType: 1, title: '请输入密码'}, function (value, i) {
                    layer.close(i);
                    var loadIndex = layer.load(2);
                    admin.req('sys/user/psw/' + obj.data.userId, {password: value}, function (res) {
                        layer.close(loadIndex);
                        if (0 === res.code) {
                            layer.msg(res.msg, {icon: 1});
                        } else {
                            layer.msg(res.msg, {icon: 2, anim: 6});
                        }
                    }, 'put');
                });
            }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(userTable)', function (obj) {
            if ('add' === obj.event) { // 添加
                showEditModel();
            } else if ('del' === obj.event) { // 删除
                var checkRows = table.checkStatus('userTable');
                if (!checkRows || !checkRows.data || 0 === checkRows.data.length) {
                    return layer.msg('请选择要删除的数据', {icon: 2, anim: 6});
                }
                var ids = checkRows.data.map(function (d) {
                    return d.userId;
                });
                doDel({ids: ids});
            } else if ('import' === obj.event) {
                showImport();
            }
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            admin.open({
                type: 1,
                title: (mData ? '修改' : '添加') + '用户',
                content: $('#userEditDialog').html(),
                success: function (layero, dIndex) {
                    if (mData) $(layero).find('[name="password"]').parent().parent().remove();
                    // 回显表单数据
                    form.val('userEditForm', mData);
                    // 表单提交事件
                    form.on('submit(userEditSubmit)', function (data) {
                        data.field.roleIds = insRoleSel.getValue('value');
                        var loadIndex = layer.load(2);
                        admin.req('sys/user', JSON.stringify(data.field), function (res) {
                            layer.close(loadIndex);
                            if (0 === res.code) {
                                layer.close(dIndex);
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload({page: {curr: 1}});
                            } else {
                                layer.msg(res.msg, {icon: 2, anim: 6});
                            }
                        }, mData ? 'put' : 'post');
                        return false;
                    });
                    // 渲染多选下拉框
                    var insRoleSel = xmSelect.render({
                        el: '#userEditRoleSel',
                        name: 'userEditRoleSel',
                        layVerify: 'required',
                        layVerType: 'tips',
                        data: roleList
                    });
                    // 回显选中角色
                    if (mData && mData.roles) {
                        insRoleSel.setValue(mData.roles.map(function (item) {
                            return item.roleId;
                        }));
                    }
                    // 渲染性别下拉
                    formX.renderSelect({
                        elem: '[lay-filter="userEditForm"] select[name="sex"]',
                        data: mSexList,
                        name: 'dictDataName',
                        value: 'dictDataId',
                        hint: '请选择性别',
                        initValue: mData ? mData.sex : undefined
                    });
                    // 禁止弹窗出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        }

        /* 删除 */
        function doDel(obj) {
            if (obj.ids) {
                admin.confirm('确定要删除选中数据吗？', function (i) {
                    layer.close(i);
                    var loadIndex = layer.load(2);
                    admin.req('sys/user/batch', JSON.stringify(obj.ids), function (res) {
                        layer.close(loadIndex);
                        if (0 === res.code) {
                            layer.msg(res.msg, {icon: 1});
                            insTb.reload({page: {curr: 1}});
                        } else {
                            layer.msg(res.msg, {icon: 2, anim: 6});
                        }
                    }, 'delete');
                });
            } else {
                var loadIndex = layer.load(2);
                admin.req('sys/user/' + obj.data.userId, function (res) {
                    layer.close(loadIndex);
                    if (0 === res.code) {
                        layer.msg(res.msg, {icon: 1});
                        insTb.reload({page: {curr: 1}});
                    } else {
                        layer.msg(res.msg, {icon: 2, anim: 6});
                    }
                }, 'delete');
            }
        }

        /* 修改用户状态 */
        form.on('switch(userTbStateCk)', function (obj) {
            var loadIndex = layer.load(2);
            admin.req('sys/user/state/' + obj.elem.value, {
                state: obj.elem.checked ? 0 : 1
            }, function (res) {
                layer.close(loadIndex);
                if (0 === res.code) {
                    layer.msg(res.msg, {icon: 1});
                } else {
                    layer.msg(res.msg, {icon: 2, anim: 6});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox', $('#userTable').next().attr('lay-filter'));
                }
            }, 'put');
        });

        /* 导入excel */
        function showImport() {
            admin.open({
                type: 1,
                title: '导入用户',
                content: ['<div style="padding: 20px 0 10px 0;text-align: center;" class="layui-text">',
                    '         <div id="userUploadDrag" class="layui-upload-drag" style="margin-bottom: 10px;">',
                    '            <i class="layui-icon">&#xe681;</i>',
                    '            <p>点击上传，或将文件拖拽到此处</p>',
                    '         </div>',
                    '         <div><a href="assets/file/用户导入模板.xlsx" target="_blank" download>下载模板</a></div>',
                    '      </div>'].join(''),
                success: function (layero, dIndex) {
                    layui.upload.render({
                        elem: '#userUploadDrag',
                        url: setter.baseServer + 'sys/user/import',
                        accept: 'file',
                        exts: 'xls|xlsx',
                        headers: {
                            Authorization: layui.setter.getToken().access_token
                        },
                        before: function (obj) {
                            layer.load(2);
                        },
                        done: function (res) {
                            layer.closeAll('loading');
                            if (0 === res.code) {
                                layer.msg(res.msg, {icon: 1});
                                layer.close(dIndex);
                                insTb.reload({page: {curr: 1}});
                            } else {
                                admin.alert(res.msg.replace(/\r\n/g, '<br/>'), {icon: 2, anim: 6, title: '导入失败'});
                            }
                        },
                        error: function () {
                            layer.msg('导入失败', {icon: 2, anim: 6});
                            layer.closeAll('loading');
                        }
                    });
                }
            });
        }

        /* 获取所有角色 */
        var loadIndex = layer.load(2);
        admin.req('sys/role', function (res) {
            layer.close(loadIndex);
            if (0 === res.code) {
                $.each(res.data, function (index, item) {
                    roleList.push({name: item.roleName, value: item.roleId});
                });
            } else {
                layer.msg(res.msg, {icon: 2});
            }
        });

        /* 获取性别字典 */
        var mSexList = [];
        admin.req('sys/dictdata', {dictCode: 'sex', sort: 'sortNumber'}, function (res) {
            layer.close(loadIndex);
            if (0 === res.code) {
                mSexList = res.data;
                formX.renderSelect({
                    elem: '[lay-filter="userTbSearchForm"] select[name="sex"]',
                    data: mSexList,
                    name: 'dictDataName',
                    value: 'dictDataId',
                    hint: '请选择性别'
                });
            } else {
                layer.msg(res.msg, {icon: 2});
            }
        });

    });
</script>
